/*
 *  Copyright 2011 jmarsden.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package cc.plural.jsonij.jpath;

import java.util.List;

import cc.plural.jsonij.Value;

/*
 * SimpleIndex Predicate Implementation. The most basic of the Predicates.
 * Results in a single specified index being retrieved during evaluation.
 *
 * @author J.W.Marsden.
 */
public class SimpleIndexPredicate extends PredicateComponent {

    public static final int LAST_INDEX;
    int index;

    static {
        LAST_INDEX = -1;
    }

    public SimpleIndexPredicate() {
        index = 0;
    }

    public SimpleIndexPredicate(int index) {
        this.index = index;
    }

    public boolean isLast() {
        return index == LAST_INDEX;
    }

    public void setLast() {
        this.index = LAST_INDEX;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    @Override
    public List<Value> evaluate(List<Value> values, List<Value> results) {
        if (isLast()) {
            int indexPredicate = -1;
            for (Value value : values) {
                if (( indexPredicate = value.size() - 1 ) >= 0) {
                    results.add(value.get(indexPredicate));
                }
            }
        } else {
            for (Value value : values) {
                if (getIndex() >= 0 && getIndex() < value.size()) {
                    results.add(value.get(getIndex()));
                } else if (getIndex() < 0 && ( value.size() + getIndex() ) >= 0) {
                    results.add(value.get(value.size() + getIndex()));
                }
            }
        }
        return results;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final SimpleIndexPredicate other = (SimpleIndexPredicate) obj;
        if (this.index != other.index) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 53 * hash + this.index;
        return hash;
    }
}
